package com.katesoft.scale4j.web.matchers;

import com.katesoft.scale4j.web.model.User;
import org.hamcrest.Description;
import org.hamcrest.TypeSafeMatcher;
import org.junit.Ignore;
import org.springframework.security.core.GrantedAuthority;

import java.util.Collection;

import static com.katesoft.scale4j.common.utils.AssertUtility.assertNotNull;

/** @author kate2007 */
@Ignore
public class HasRoleMatcher extends TypeSafeMatcher<User> {
   private final String role;

   public HasRoleMatcher(final String role) {
      this.role = role;
      assertNotNull(role, "user role can not be null");
   }

   @Override
   public void describeTo(final Description description) {
      description.appendText("has role = ").appendValue(role);
   }

   @Override
   public boolean matchesSafely(final User user) {
      if (user == null) {
         return false;
      }
      final Collection<GrantedAuthority> authorities = user.getAuthorities();
      if (authorities == null) {
         return false;
      }
      for (final GrantedAuthority grantedAuthority : authorities) {
         if (grantedAuthority.getAuthority().equals(role)) {
            return true;
         }
      }
      return false;
   }
}
